<template>
    <div>
        <!-- 添加内容容器ref -->
        <div>
            <el-tabs v-model="activeTab">
                <el-tab-pane label="个人资料" name="profile">
                    <el-form :model="currentUser" label-width="100px" label-position="left">
                        <el-form-item label="用户名">
                            <el-input v-model="currentUser.username" />
                        </el-form-item>
                        <el-form-item label="新密码">
                            <el-input v-model="currentUser.newPassword" type="password" show-password />
                        </el-form-item>
                        <el-form-item label="确认密码">
                            <el-input v-model="currentUser.confirmPassword" type="password" show-password />
                        </el-form-item>
                        <el-form-item label="角色">
                            <el-input :value="formatRole(currentUser)" disabled />
                        </el-form-item>
                        <el-form-item label="最后登录时间">
                            <el-input v-model="currentUser.lastLoginTime" disabled />
                        </el-form-item>
                        <el-form-item label="最后登录IP">
                            <el-input v-model="currentUser.lastLoginIp" disabled />
                        </el-form-item>
                        <el-form-item>
                            <el-button type="primary" @click="updateCurrentUser">保存修改</el-button>
                        </el-form-item>
                    </el-form>
                </el-tab-pane>

                <el-tab-pane label="用户管理" name="user-manage">
                    <!-- 删除内容容器ref -->
                    <div style="position: relative;">
                        <div style="margin-bottom: 20px;">
                            <el-input v-model="searchUser" placeholder="搜索用户" style="width: 300px;" />
                        </div>
                        <el-table :data="filteredUsers" ref="contentContainer">
                            <el-table-column prop="username" label="用户名"></el-table-column>
                            <el-table-column prop="role" label="角色" :formatter="formatRole"></el-table-column>
                            <el-table-column prop="lastLoginTime" label="最后登录时间"
                                :formatter="formatLastLoginTime"></el-table-column>
                            <el-table-column prop="lastLoginIp" label="最后登录IP"></el-table-column>
                            <el-table-column label="操作" width="150">
                                <template #default="{ row }">
                                    <el-button size="small" type="primary" @click="handleEditUser(row)">编辑</el-button>
                                    <el-button size="small" type="danger" @click="handleDeleteUser(row)">删除</el-button>
                                </template>
                            </el-table-column>
                        </el-table>
                        <el-dialog v-model="dialogVisible" title="编辑用户" width="500px">
                            <el-form :model="form" label-width="80px">
                                <el-form-item label="用户名">
                                    <el-input v-model="form.username" />
                                </el-form-item>
                                <el-form-item label="角色">
                                    <el-select v-model="form.role" placeholder="请选择角色" style="width: 300px;">
                                        <el-option v-for="role in roleOptions" :key="role.value" :label="role.label"
                                            :value="role.value" />
                                    </el-select>
                                </el-form-item>
                                <el-form-item label="修改密码">
                                    <el-switch v-model="enablePasswordChange" />
                                </el-form-item>
                                <el-form-item v-if="enablePasswordChange" label="新密码">
                                    <el-input v-model="form.newPassword" type="password" show-password />
                                </el-form-item>
                                <el-form-item v-if="enablePasswordChange" label="确认密码">
                                    <el-input v-model="form.confirmPassword" type="password" show-password />
                                </el-form-item>
                                <el-form-item>
                                    <el-button type="primary" @click="submitEditUser">提交</el-button>
                                    <el-button @click="dialogVisible = false">取消</el-button>
                                </el-form-item>
                            </el-form>
                        </el-dialog>
                    </div>
                </el-tab-pane>
            </el-tabs>
        </div>
    </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import api from '../services/api';
import dayjs from 'dayjs';
import { ElMessageBox } from 'element-plus';

// 添加初始化逻辑
const users = ref([]);

onMounted(async () => {
    try {
        await Promise.all([
            api.getCurrentUser().then(res => {
                currentUser.value = res.data;
                currentUser.value.lastLoginTime = dayjs(currentUser.value.lastLoginTime).format('YYYY-MM-DD HH:mm:ss');
            }),
            api.getUsers().then(res => {
                users.value = res.data;
            })
        ]);
    } catch (error) {
        console.error('初始化数据失败:', error);
    }
});

// 修改过滤逻辑处理空值情况
const filteredUsers = computed(() =>
    users.value.filter(user =>
        (user.username || '').includes(searchUser.value) ||
        (user.role || '').includes(searchUser.value)
    )
);

// 当前登录用户信息
const currentUser = ref({
    id: null,
    username: '',
    role: '',
    lastLoginTime: '',
    lastLoginIp: '',
    newPassword: '',
    confirmPassword: ''
});

const updateCurrentUser = async () => {
    try {
        if (currentUser.value.newPassword && currentUser.value.newPassword !== currentUser.value.confirmPassword) {
            alert('两次密码输入不一致');
            return;
        }

        const updateData = {
            ...currentUser.value,
            password: currentUser.value.newPassword || undefined
        };
        delete updateData.newPassword;
        delete updateData.confirmPassword;

        await api.updateUser(currentUser.value.id, updateData);
        alert('修改成功');
        currentUser.value.newPassword = '';
        currentUser.value.confirmPassword = '';
    } catch (error) {
        console.error('更新用户信息失败:', error);
    }
};

// 用户搜索功能
const searchUser = ref('');

// 用户操作方法
const handleEditUser = (user) => {
    form.value = {
        ...user,
        newPassword: '',
        confirmPassword: ''
    };
    dialogVisible.value = true;
};

const handleDeleteUser = async (user) => {
    try {
        await ElMessageBox.confirm('确定要删除该用户吗？', '警告', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        });

        await api.deleteUser(user.id);
        users.value = users.value.filter(u => u.id !== user.id);
    } catch (error) {
        if (error !== 'cancel') {
            console.error('删除用户失败:', error);
        }
    }
};

// 添加标签页激活状态控制
const activeTab = ref('profile');

// 添加编辑用户相关响应式数据
const dialogVisible = ref(false);
const form = ref({
    id: null,
    username: '',
    role: '',
    newPassword: '',
    confirmPassword: ''
});

// 添加角色选项
const roleOptions = [
    { label: '管理员', value: 'admin' },
    { label: '用户', value: 'user' }
];

// 添加密码修改开关状态
const enablePasswordChange = ref(false);

// 添加用户编辑提交逻辑
const submitEditUser = async () => {
    try {
        if (enablePasswordChange.value) {
            if (form.value.newPassword && form.value.newPassword !== form.value.confirmPassword) {
                alert('两次密码输入不一致');
                return;
            }
        }

        const updateData = {
            ...form.value,
            password: enablePasswordChange.value ? form.value.newPassword : undefined
        };
        delete updateData.newPassword;
        delete updateData.confirmPassword;

        await api.updateUser(form.value.id, updateData);
        users.value = users.value.map(u => u.id === form.value.id ? { ...u, ...updateData } : u);
        dialogVisible.value = false;
        enablePasswordChange.value = false; // 重置开关状态
        alert('修改成功');
    } catch (error) {
        console.error('更新用户信息失败:', error);
    }
};

const formatLastLoginTime = (row, column, cellValue) => {
    return dayjs(cellValue).format('YYYY-MM-DD HH:mm:ss');
};

// 添加角色格式化方法
const formatRole = (row) => {
    const found = roleOptions.find(option => option.value === row.role);
    return found ? found.label : row.role;
};
</script>

<style scoped>
.el-form-item {
    margin-bottom: 20px;
}

.el-form-item .el-input {
    width: 300px;
}
</style>
